<?php
namespace app\api\controller;


use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;



/**
 * 微信公众号登录
 */
class Wxgzh extends Api{



//公众号登录
    public function login(){

        $appid = 'wxd9a0863d49ebf4fb'; //公众号信息
        $secret ='260bfa8da9a21c3a7bd28c0a808c10bd';//公众号信息

        $code = $this->request->param('code');

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";


        $ret = file_get_contents($url);
        $ret = json_decode($ret, 'true');


        $access_token = $ret['access_token'];
        $openid = $ret['openid'];


        $urlb = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";


        $rets = file_get_contents($urlb);

        $rets = json_decode($rets, 'true');


        if (isset($rets['openid'])) {


            $infos=Db::name('user_gzh')->where(['openid'=>$rets['openid']])->find();

            if (!$infos){
                Db::name('user_gzh')->data(['name'=>$rets['nickname'],'unionid'=>$rets['unionid'],'openid'=>$rets['openid']])->insert();
            }


//            $url=$this->geturl();

            $url="https://mp.weixin.qq.com/s?__biz=Mzg2ODgxODI4MA==&mid=2247485344&idx=2&sn=0b2c96fce4c18e7fc0cd05bedf22942f&chksm=cea7cba7f9d042b1ee8145555b0701a60092d2164e3f345555c17045f15808cfaa0e2dd4ac67#rd";

            $this->success('操作成功!',$url);

        } else {


            $this->error("注册失败,请重试!");
        }
    }



    public function getaccess_token($appid, $appsecret)  {

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
        $ret=file_get_contents($url);
        $ret=json_decode($ret,true);

        return $ret;


        // close curl resource to free up system resources
    }



    public function https_request($url = '', $param = [], $contentType = ''){
        $ch = curl_init();

        // 请求地址
        curl_setopt($ch, CURLOPT_URL, $url);

        // 请求参数类型
        $param = $contentType == 'json' ? json_encode($param) : $param;

        // 关闭https验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);


        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);


        // 返回的数据是否自动显示
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 执行并接收响应结果
        $output = curl_exec($ch);

        // 关闭curl
        curl_close($ch);

        return $output !== false ? $output : false;
    }


    //获取小程序短地址
    public function geturl (){

        $access_token = $this->getaccess_token('wx90f1aeade7f00d83', '8cd39e467e18db368ec7e76da7cafcd4');

        $access_tokens = $access_token['access_token'];

        $url='https://api.weixin.qq.com/wxa/generatescheme?access_token='.$access_tokens;

        $response=$this->https_request($url,[],'');

        $response=json_decode($response,true);

        return $response['openlink'];
    }


    //curl请求
    public  function curl_post($url, $data = array())
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    //发送模板消息 新访客
    public function do_send()
    {
        $unionid=$this->request->param('unionid');
        $uid=$this->request->param('uid');

        $to=Db::name('user_gzh')->where(['unionid'=>$unionid])->find();
        $user=Db::name('user')->where('id','eq',$uid)->find();


        $appid = 'wxd9a0863d49ebf4fb'; //公众号
        $appsecret ='260bfa8da9a21c3a7bd28c0a808c10bd';//公众号

        $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        //获取access_token
        $json_token = $this->curl_post($access_token_url);
        $access_token1 = json_decode($json_token, true);
        $access_token2 = $access_token1['access_token'];
        //模板消息
        $json_template = $this->json_tempalte($to['openid'],$user['mobile']);

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token2;
        $res = $this->curl_post($url, urldecode($json_template));
        $res = json_decode($res, true);
        if ($res['errcode'] == 0) {
            echo '发送成功';
        } else {
            echo '发送失败';
        }
    }

    //将模板消息json格式化
    public function json_tempalte($openid,$mobile)
    {
        $url=$this->geturl();

        $mobile=substr($mobile,0,3).'****'.substr($mobile,7,4);
        //模板消息
        $template = [
            'touser' => $openid,  //前面获取的openid
            'template_id' => "X7mddeXXLVwewZVS13kCuwayNC-OrGTrlwZUloTa7_0", //前面新增的模板id
            'url' => $url, //点击模板消息会跳转的链接
            "miniprogram"=>['appid'=>'wx90f1aeade7f00d83','pagepath'=>'/pages/index/index'],
            'topcolor' => "#7B68EE",
            'data' => array(
                //这里在测试号是没法显示的，但是在正式的模板是这样的数据
                'first' => array('value' => urlencode("尊敬的用户,您好!"), 'color' => "#333333"),
                'keyword1' => array('value' => urlencode('新用户'), 'color' => '#333333'),
                'keyword2' => array('value' => urlencode($mobile), 'color' => '#333333'),
                'keyword3' => array('value' => urlencode(date('Y-m-d h:i')), 'color' => '#333333'),
                'remark' => array('value' => urlencode('点击进入小程序查看！'), 'color' => '#333333')
            )
        ];
        $json_template = json_encode($template);
        return $json_template;
    }



    //关注信息
    public function do_sendb()
    {
        $unionid=$this->request->param('unionid');
        $title=$this->request->param('title');

        $to=Db::name('user_gzh')->where(['unionid'=>$unionid])->find();


        $appid = 'wxd9a0863d49ebf4fb'; //公众号
        $appsecret ='260bfa8da9a21c3a7bd28c0a808c10bd';//公众号

        $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        //获取access_token
        $json_token = $this->curl_post($access_token_url);
        $access_token1 = json_decode($json_token, true);
        $access_token2 = $access_token1['access_token'];
        //模板消息
        $json_template = $this->json_tempalteb($to['openid'],'有用户喜欢了你');

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token2;
        $res = $this->curl_post($url, urldecode($json_template));
        $res = json_decode($res, true);
        if ($res['errcode'] == 0) {
            echo '发送成功';
        } else {
            echo '发送失败';
        }

        die();
    }

    //将模板消息json格式化
    public function json_tempalteb($openid,$title)
    {
        $url=$this->geturl();

        //模板消息
        $template = [
            'touser' => $openid,  //前面获取的openid
            'template_id' => "_OjOsROLrIisW1f7fWMsdIVmA7K1vWzZwngPYU5HYNc", //前面新增的模板id
            'url' => $url, //点击模板消息会跳转的链接
            "miniprogram"=>['appid'=>'wx90f1aeade7f00d83','pagepath'=>'/pages/message/index'],
            'topcolor' => "#7B68EE",
            'data' => array(
                //这里在测试号是没法显示的，但是在正式的模板是这样的数据
                'first' => array('value' => urlencode("尊敬的用户,您好!"), 'color' => "#333333"),
                'keyword1' => array('value' => urlencode(date('Y-m-d H:i')), 'color' => '#333333'),
                'keyword2' => array('value' => urlencode($title), 'color' => '#333333'),
                'remark' => array('value' => urlencode('点击进入小程序查看！'), 'color' => '#333333')
            )
        ];
        $json_template = json_encode($template);
        return $json_template;
    }

    //test
    public function do_sendc()
    {
        $unionid=$this->request->param('unionid');
        $title=$this->request->param('title');

        $to=Db::name('user_gzh')->where(['unionid'=>$unionid])->find();


        $appid = 'wxd9a0863d49ebf4fb'; //公众号
        $appsecret ='260bfa8da9a21c3a7bd28c0a808c10bd';//公众号

        $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        //获取access_token
        $json_token = $this->curl_post($access_token_url);
        $access_token1 = json_decode($json_token, true);
        $access_token2 = $access_token1['access_token'];
        //模板消息
        $json_template = $this->json_tempalteb($to['openid'],'您收到一个新的信息!');

        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token2;
        $res = $this->curl_post($url, urldecode($json_template));
        $res = json_decode($res, true);
        if ($res['errcode'] == 0) {
            echo '发送成功';
        } else {
            echo '发送失败';
        }

        die();
    }



}
